package cn.ihelloworld.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.ihelloworld.bean.Comment;
import cn.ihelloworld.dao.ICommentDao;
import cn.ihelloworld.dao.Pagation;

@Repository
public class CommentDaoImpl implements ICommentDao {
	
	@Autowired
	private SessionFactory sf;

	@Override
	public Comment get(String id) {
		return (Comment) sf.getCurrentSession().get(Comment.class, id);
	}

	@Override
	public List<Comment> select(Comment t) {
		Criteria criteria=sf.getCurrentSession().createCriteria(Comment.class);
		if(t!=null){
			if(t.getAuthor()!=null&&!t.getAuthor().equals("")){
				criteria.add(Restrictions.eq("author", t.getAuthor()));
			}
			if(t.getArticle()!=null&&t.getArticle().getTitle()!=null&&!t.getArticle().getTitle().equals("")){
				criteria.add(Restrictions.eq("article.id", t.getArticle().getTitle()));
			}
		}
		List<Comment> list=criteria.list();
		return list;
	}

	@Override
	public Pagation<Comment> selectForPage(Comment t, int currentPage,
			int pageSize) {
		Pagation<Comment> pagation=new Pagation<Comment>();
		int start=currentPage==0?0:(currentPage-1)*pageSize;
		int end=currentPage*pageSize;
		pagation.setStart(start);
		pagation.setEnd(end);
		List<Comment> list=new ArrayList<Comment>();
		Criteria criteria=sf.getCurrentSession().createCriteria(Comment.class);
		criteria.addOrder(Order.desc("createDate"));
		if(t!=null){
			if(t.getAuthor()!=null&&!t.getAuthor().equals("")){
				criteria.add(Restrictions.ilike("author", t.getAuthor(),MatchMode.START));
			}
			if(t.getArticleId()!=null&&!t.getArticleId().equals("")){
				criteria.add(Restrictions.eq("article.id", t.getArticleId()));
			}
			Long count=(Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
			pagation.setTotal(count.intValue());
			criteria.setProjection(null);
			criteria.setFirstResult(start);
			criteria.setMaxResults(end);
			list=criteria.list();
		}
		pagation.setRs(list);
		return pagation;
	}

	@Override
	public void saveOrUpdate(Comment t) {
		sf.getCurrentSession().saveOrUpdate(t);
	}

	@Override
	public void delete(String id) {
		sf.getCurrentSession().delete(id);
	}

	@Override
	public void delete(String[] ids) {
		StringBuffer sb=new StringBuffer("delete Article where id in");
		sb.append("(");
		for(int i=0;i<ids.length;i++){
			sb.append("'");
			sb.append(ids[i]);
			sb.append("'");
			if(i!=ids.length-1){
				sb.append(",");
			}
		}
		sb.append(")");
		sf.getCurrentSession().createQuery(sb.toString()).executeUpdate();
	}

}
